package com.zxl.always.on.display.base;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

import java.util.List;

/**
 * Created by Administrator on 2016/7/13.
 */

public abstract class BaseAppCompatFragment extends Fragment {

    public AppCompatActivity getAppCompatActivity() {
        FragmentActivity activity = getActivity();
        if (activity != null && activity instanceof AppCompatActivity) {
            return ((AppCompatActivity) activity);
        }
        return null;
    }

    /**
     * 返回事件
     * @return
     */
    protected boolean onBackPressed() {
        return handleBackPress(getChildFragmentManager());
    }

    /**
     * 将back事件分发给 FragmentManager 中管理的子Fragment，如果该 FragmentManager 中的所有Fragment都
     * 没有处理back事件，则尝试 FragmentManager.popBackStack()
     *
     * @return 如果处理了back键则返回 <b>true</b>
     */
    public static boolean handleBackPress(FragmentManager fragmentManager) {
        List<Fragment> fragments = fragmentManager.getFragments();

        if (fragments == null) {
            return false;
        }

        for (int i = fragments.size() - 1; i >= 0; i--) {
            Fragment child = fragments.get(i);

            if (isFragmentBackHandled(child)) {
                return true;
            }
        }

        if (fragmentManager.getBackStackEntryCount() > 0) {
            fragmentManager.popBackStack();
            return true;
        }
        return false;
    }

    /**
     * 判断Fragment是否处理了Back键
     *
     * @return 如果处理了back键则返回 <b>true</b>
     */
    public static boolean isFragmentBackHandled(Fragment fragment) {
        return fragment != null && fragment.isVisible() && fragment.getUserVisibleHint()  && fragment instanceof BaseAppCompatFragment && ((BaseAppCompatFragment) fragment).onBackPressed();
    }


}
